package com.yjx.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.yjx.util.RedisUtil;
import com.yjx.util.ResourceUtil;
import com.yjx.vo.UserVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import javax.annotation.Resource;

public class TokenFilter implements GlobalFilter, Ordered {
    @Resource
    private RedisUtil redisUtil;
    @Value("${loginPath}")
    private String loginPath;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("TokenFilter");
        JsonMapper jsonMapper = new JsonMapper();
        String path = exchange.getRequest().getPath().toString();

        if (loginPath.equals(path)){
            //登录操作
            return chain.filter(exchange);
        }

        String token = exchange.getRequest().getHeaders().getFirst("token");
        String userJson = redisUtil.get(token);
        if (userJson == null || userJson.equals("")){
            System.out.println("token失效");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        try {
            UserVo userVo= jsonMapper.readValue(userJson,UserVo.class);
            Boolean result = ResourceUtil.checkResource(path,userVo.getResourceVoList());
            if (!result){
                System.out.println("无操作权限");
                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                return exchange.getResponse().setComplete();
            }
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
